'use strict';
const Controller = require('egg').Controller;
const fs = require('fs');
const path = require('path');
var pump = require('pump')
class UploadController extends Controller {
  async picture() {
    const createPic= () => {
        var now=new Date(); 
        var year = now.getFullYear(); //得到年份
        var month = now.getMonth();//得到月份
        var date = now.getDate();//得到日期
        var hour = now.getHours();//得到小时
        var minu = now.getMinutes();//得到分钟
        month = month + 1;
        if (month < 10) month = "0" + month;
        if (date < 10) date = "0" + date;
        var number = now.getSeconds()%43; //这将产生一个基于目前时间的0到42的整数。
        var time = year + month + date+hour+minu;
        return time+"_"+number;
    }
    const parts  = await this.ctx.multipart();
    const pictureName = createPic();
    let target = {
      edition: '',
      moduleName: '',
      type: 'daily',
    }
    let word;
    while ((word = await parts())){
      if (!word.filename) return ;
      const str = `app/public/uploadPicture/${pictureName}.png`;
      const writeStream = fs.createWriteStream(str);
      await pump(word, writeStream); //写入并销毁当前流   (egg  demo提供的)
    }
    
    this.ctx.body = this.ctx.success(`public/uploadPicture/${pictureName}.png`);
  }
  async index() {
    const parts  = await this.ctx.multipart();
    let target = {
      edition: '',
      moduleName: '',
      type: 'daily',
    }
    let word;
    while ((word = await parts())){
        if(Array.isArray(word)){
          Object.keys(target).forEach(v => {
            if(v === word[0]){
              target[v] = word[1]
            }
          });
        }else{
          if (!word.filename) return ;
          const str = `app/public/begin/` + path.basename(word.filename);
          const writeStream = fs.createWriteStream(str);
          await pump(word, writeStream); //写入并销毁当前流   (egg  demo提供的)
        }
    }
    console.log(target)
    // toDo 需要在此处判断权限，是否有权限写入文件
    await this.operateFile(target);

    let sql =  `select * from module_list where module_name = "${target.moduleName}" and edition = "${target.edition}" and type = "${target.type}"`
    console.log(sql)
    const moduleList = await this.app.mysql.query(sql);
    console.log(moduleList)
    if(moduleList && moduleList.length){
      this.ctx.success("发布成功")
    }else{
      let param ={
        edition: target.edition,
        module_name: target.moduleName,
        type: target.type,
      }
      await this.app.mysql.insert('module_list', param);
      this.ctx.success("发布成功")
    }

    

    this.ctx.body = 'dsa';
  }
  // path
  async operateFile(target){
    const basePath = `app/public/begin/`;
    const movePath = `app/public/${target.moduleName}/${target.edition}/${target.type}/`;
    await this.ctx.dirExists(movePath);
    const fileArr = ['index.js', 'mock.json', 'schema.json', 'vue-ssr-server-bundle.json', 'vue-ssr-client-manifest.json']
    fileArr.forEach(v => {
      this.ctx.move(basePath+v, movePath+v);
    })
  }
}

module.exports = UploadController;
